from  selenium import  webdriver
from  selenium.webdriver.common.by import By
from  selenium.webdriver.chrome.service import Service
from  selenium.webdriver.common.keys import Keys
import  time

service = Service("d:/chromedriver/chromedriver/chromedriver.exe")
driver = webdriver.Chrome(service=service)

#打开必应
driver.get('https://cn.bing.com/')
#找到搜索框并输入关键字
search_box = driver.find_element(By.NAME,'q')
search_box.send_keys('邓丽君')
#按下回车键（python脚本模拟按下回车键）
search_box.send_keys(Keys.RETURN)
#等待搜索结果加载
time.sleep(3)
#获取页面标题
page_title = driver.title
#写入文件
with open('bing.txt','w', encoding='utf-8') as  file:
    file.write(f'页面标题:{page_title}\n')
    #获取搜索结果
    search_results = driver.find_element(By.CSS_SELECTOR,"h2 a")
    for idx,result in enumerate(search_results,start=1):
        result_title = result.text
        result_link = result.get_attribute('href')
        file.write(f'结果{idx}:\n标题:{result_title}\n链接:{result_link}\n\n')
time.sleep(3)
driver.quit()